<template>
    <div>
        <a-spin :spinning="state.loading">
            <div>
                选择图片上传
            </div>
            <a-upload-dragger
                    name="file"
                    :multiple="false"
                    :file-list="state.fileList"
                    :before-upload="beforeUpload"
                    @remove="handleRemove"
            >
                <p class="ant-upload-drag-icon">
                    <inbox-outlined></inbox-outlined>
                </p>
                <p class="ant-upload-text">点击获取拖拽选择文件上传</p>
            </a-upload-dragger>
            <div style="margin-top: 20px;">
                <a-button type="primary" @click="handleUpload">
                    上传
                </a-button>
            </div>


            <div style="margin:10px 0">
                <a-image :src="state.src" :width="200"></a-image>
            </div>
        </a-spin>
    </div>
</template>
<script lang="ts" setup>
    import { reactive,defineProps,defineEmits,watch } from 'vue';
    import { message } from 'ant-design-vue';
    import {uploadImgFile} from '@/service/upload/index'
    import {globalEnv} from '@/utils/index.ts'

    const env=globalEnv()

    const props=defineProps({
        id:''
    })

    const emit=defineEmits(['confirm'])
    const state:any=reactive({
        loading:false,
        fileList:[],
        src:''
    })
    const beforeUpload=(file:File)=>{
        if(file.type.includes('image')){
            state.fileList=[file]
        }
        else{
            message.warn('请上传图片')
        }
        return false;
    }

    const handleRemove = (file) => {
        state.fileList=[]
    };

    watch(()=>props.id,
        (id)=>{
            state.fileList=[]
            if(id){

                state.src=env.VITE_APP_HOST+`/cloudApi/api/media/render?id=${id}`
                console.log('src', state.src)
            }
        },{
            deep:true,
            immediate:true
        })

    const handleUpload = async () => {
        if(!state.fileList.length){
            return message.warn('请选择文件')
        }
        const formData = new FormData();
        state.fileList.forEach((file: any) => {
            formData.append('file', file as any);
        });
        state.loading = true;
        try{
            const res=await uploadImgFile(formData)
            console.log('res',res)
            const id=res.data.data.id
            emit('confirm',id)
            message.success('上传成功！')
        }
        catch (e) {
            message.error(JSON.stringify(e))
        }
        state.loading = false;
    };

</script>
